<template>
  <div class="swipers">
    <!-- <ul
      @touchstart="touchStart"
      @touchmove="touchMove"
      @touchend="touchEnd"
      :style="activeStyle"
    >
      <li v-for="(item, index) in imgs" :key="index">
        <img :src="item.img" alt="" />
      </li>
    </ul> -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      // imgs: [
      //   { img: "../assets/img/01.png" },
      //   { img: "../assets/img/02.png" },
      //   { img: "../assets/img/03.png" },
      //   { img: "../assets/img/04.png" },
      // ],
      swiper: [],
      activeStyle: {
        transition: "none",
        left: "-100%",
      },
      dir: "left", // 标记用户滑动的方向
      startPos: 0, // 记录用户触摸的开始点
      isWork: true, // 标记动画是否能够执行
    };
  },
  mounted() {
    // 轮播图
    setInterval(() => {
      this.touchEnd();
    }, 1000);
  },
  methods: {
    touchStart(e) {
      this.startPos = e.touches[0].pageX;
    },
    touchMove(e) {
      if (e.touches[0].pageX - this.startPos > 0) {
        this.dir = "right";
      } else {
        this.dir = "left";
      }
    },
    touchEnd() {
      if (this.isWork) {
        this.isWork = false;
        if (this.dir == "right") {
          this.activeStyle = {
            transition: "left 1s",
            left: "0",
          };

          setTimeout(() => {
            let item = this.swiper.pop();
            this.swiper.unshift(item);
            this.activeStyle = {
              transition: "none",
              left: "-100%",
            };
            this.isWork = true;
          }, 1000);
        } else {
          this.activeStyle = {
            transition: "left 1s",
            left: "-200%",
          };

          setTimeout(() => {
            let item = this.swiper.shift();
            this.swiper.push(item);
            this.activeStyle = {
              transition: "none",
              left: "-100%",
            };
            this.isWork = true;
          }, 1000);
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.swipers {
  width: 5rem;
  height: 3rem;
  // background: forestgreen;
  right: 0.25rem;
  margin: auto;
  overflow: hidden;

  ul {
    width: 400%;
    height: 6rem;
    position: relative;
    > li {
      width: 20%;
      height: 6rem;
      float: left;
      text-align: center;
      img {
        width: 5rem;
        height: 3rem;
      }
    }
  }
}
</style>
